//
//  SuXiBirthdayVC.swift
//  SuXianCalculator
//
//  Created by 李东 on 2024/3/29.
//

import UIKit
import Alamofire

class SuXiBirthdayVC: SuXiBaseVC {
    
    @IBOutlet weak var selectView: UIView!
    
    @IBOutlet weak var dateLabel: UILabel!
    
    @IBOutlet weak var startBtn: UIButton!
    
    var m : Int = 0
    var d : Int = 0
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "生日性格"
        selectView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectDateHandle(sender:))))
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "M d"
        return temp
    }()
    
    lazy var df1: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy-MM-dd"
        return temp
    }()


    @IBAction func startHandle(_ sender: Any) {
        startCheck(m: m, d: d)
    }
    
    @objc func selectDateHandle(sender: UIGestureRecognizer) {
        let vc = SuXiDatePicker()
        vc.modalPresentationStyle = .overCurrentContext
        vc.finish = {[weak self] tempDate in
            guard let self = self else {
                return
            }
            self.dateLabel.text = self.df1.string(from: tempDate)
            let list = self.df.string(from: tempDate).components(separatedBy: " ")
            self.m = Int(list[0]) ?? 0
            self.d = Int(list[1]) ?? 0
            self.startBtn.isEnabled = true
        }
        present(vc, animated: true)
    }
    
    func startCheck(m: Int, d: Int) {
        showHUD()
        AF.request("https://apis.tianapi.com/dob/index?key=88133bd9f114118e733c37ca386224e8&m=\(m)&d=\(d)", method: .get).responseJSON {[weak self] (response) in
            guard let self = self else {
                return
            }
            self.dismissHUD()
            guard let json = response.value as? [String: Any] else{
                return
            }
            if let temp = SuXiApiModel.deserialize(from: json) {
                if temp.code == 200 {
                    self.navigationController?.pushViewController(SuXiResultVC(model: temp.result), animated: true)
                }else {
                    self.showHUDTextOnly("解析失败")
                }
                
            }
        }
    }
}
